package com.sinochem.iot.rule.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sinochem.iot.common.util.BeanHelper;
import com.sinochem.iot.common.vo.TriggerRuleVo;
import com.sinochem.iot.rule.common.RestCode;
import com.sinochem.iot.rule.common.RestResponse;
import com.sinochem.iot.rule.model.Trigger;
import com.sinochem.iot.rule.model.TriggerExample;
import com.sinochem.iot.rule.model.TriggerRule;
import com.sinochem.iot.rule.model.TriggerRuleStore;
import com.sinochem.iot.rule.service.TriggerRuleDetailService;
import com.sinochem.iot.rule.service.TriggerRuleService;
import com.sinochem.iot.rule.service.TriggerRuleStoreService;
import com.sinochem.iot.rule.service.TriggerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;


@Api(value = "rule", description = "触发器管理", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("trigger")
public class TriggerController {


    private static final Logger logger = LoggerFactory.getLogger(TriggerController.class);
    @Autowired
    private TriggerService triggerService;
    @Autowired
    private TriggerRuleService triggerRuleService;
    @Autowired
    private TriggerRuleStoreService triggerRuleStoreService;
    @Autowired
    private TriggerRuleDetailService triggerRuleDetailService;

    /**
     * 分页查询触发器信息
     *
     * @param trigger
     * @return
     */
    @ApiOperation(value = "分页查询触发器信息")
    @ApiImplicitParam(name = "trigger", value = "触发器实体")
    @RequestMapping(value = "queryTriggerPaginate", method = RequestMethod.POST)
    public RestResponse<PageInfo<Trigger>> queryTriggerPaginate(@RequestBody Trigger trigger) {
        logger.info("查询触发器信息参数" + JSON.toJSONString(trigger));
        PageHelper.startPage(trigger.getPageNum(), trigger.getPageSize(), trigger.getOrderBy());
        TriggerExample example = new TriggerExample();
        example.setOrderByClause(trigger.getOrderBy());
        TriggerExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(trigger.getTriName())) {
            criteria.andTriNameLike("%" + trigger.getTriName() + "%");
        }
        if (!StringUtils.isEmpty(trigger.getStatus())) {
            criteria.andStatusEqualTo(trigger.getStatus());
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(trigger.getUsername())) {
            criteria.andUserNameEqualTo(trigger.getUsername());
        }
        example.setOrderByClause(trigger.getOrderBy());

        List<Trigger> triggers = triggerService.selectByExample(example);
        PageInfo<Trigger> pageInfo = new PageInfo<>(triggers);
        return RestResponse.success(pageInfo);
    }

    /**
     * 添加触发器
     *
     * @param trigger
     * @return
     */
    @ApiOperation(value = "添加触发器")
    @ApiImplicitParam(name = "trigger", value = "触发器实体")
    @RequestMapping(value = "addTrigger", method = RequestMethod.POST)
    public RestResponse addTrigger(@RequestBody Trigger trigger) {
        logger.info("添加触发器参数" + JSON.toJSONString(trigger));

        RestResponse restResponse = checkTrigger(trigger);
        if (restResponse.getCode() != 0) {
            return restResponse;
        }
        BeanHelper.onInsert(trigger);
        triggerService.insert(trigger);

        return RestResponse.success();
    }


    /**
     * 删除触发器
     *
     * @param trigger
     * @return
     */
    @ApiOperation("删除触发器")
    @ApiImplicitParam(name = "id", value = "触发器")
    @RequestMapping(value = "delTrigger", method = RequestMethod.POST)
    public RestResponse delTriggerById(@RequestBody Trigger trigger) {
        logger.info("删除触发器参数" + JSON.toJSONString(trigger));

        Integer id = trigger.getId();
        triggerService.delTriggerById(id);
        return RestResponse.success();
    }

    /**
     * 修改触发器
     *
     * @param trigger
     * @return
     */
    @ApiOperation("修改触发器")
    @ApiImplicitParam(name = "trigger", value = "触发器实体")
    @RequestMapping(value = "updTrigger", method = RequestMethod.POST)
    public RestResponse updTrigger(@RequestBody Trigger trigger) {
        logger.info("修改触发器参数" + JSON.toJSONString(trigger));

        RestResponse restResponse = checkTrigger(trigger);
        if (restResponse.getCode() != 0) {
            return restResponse;
        }
        triggerService.updateByPrimaryKeySelective(trigger);
        return RestResponse.success();
    }

    /**
     * 修改触发器状态
     *
     * @param trigger
     * @return
     */
    @ApiOperation("修改触发器状态")
    @ApiImplicitParam(name = "trigger", value = "触发器实体")
    @RequestMapping(value = "updTriggerStatus", method = RequestMethod.POST)
    public RestResponse updTriggerStatus(@RequestBody Trigger trigger) {
//        logger.info("修改触发器状态"+ JSON.toJSONString(trigger));

        Trigger trigger1 = triggerService.selectByPrimaryKey(trigger.getId());
        TriggerRule triggerRule = triggerRuleService.getTriggerRuleByTriId(trigger.getId());
        //触发器未启动
        if (trigger1.getStatus() == 0) {

            //没有添加触发规则，不能启动
            if (triggerRule == null) {
                return RestResponse.error(RestCode.Trigger_Rule_Null);
            }

        }
        triggerService.updTriggerStatus(trigger,triggerRule);

        return RestResponse.success();
    }

    /**
     * 获取触发器
     *
     * @param query
     * @return
     */
    @ApiOperation("获取触发器")
    @ApiImplicitParam(name = "id", value = "触发器id")
    @RequestMapping(value = "getTriggerById", method = RequestMethod.POST)
    public RestResponse getTriggerById(@RequestBody Trigger query) {
        Trigger trigger = triggerService.selectByPrimaryKey(query.getId());
        return RestResponse.success(trigger);
    }

    /**
     * 添加触发器规则
     *
     * @param triggerRule
     * @return
     */
    @ApiOperation("添加触发器规则")
    @ApiImplicitParam(name = "triggerRule", value = "TriggerRule")
    @RequestMapping(value = "addTriggerRule", method = RequestMethod.POST)
    public RestResponse addTriggerRule(@RequestBody TriggerRule triggerRule) {
        logger.info("添加规则参数" + JSON.toJSONString(triggerRule));

//        TriggerRule triggerRule=JsonUtils.map2obj((Map<?, ?>) map.get(ConstMap.RULE),TriggerRule.class);
        RestResponse restResponse = checkTriggerRule(triggerRule);
        if (restResponse.getCode() != 0) {
            return restResponse;
        }

        int result = triggerRuleService.addTriggerRule(triggerRule);
//        if (result == 0)
//            return RestResponse.error(RestCode.Trigger_Rule_Exist);

        return RestResponse.success();
    }

    /**
     * 获取触发器规则
     *
     * @param query
     * @return
     */
    @ApiOperation("获取触发器规则")
    @ApiImplicitParam(name = "triId", value = "触发器id")
    @RequestMapping(value = "getTriggerRuleByTriId", method = RequestMethod.POST)
    public RestResponse getTriggerRuleByTriId(@RequestBody TriggerRule query) {
        Map<String, Object> map = triggerRuleService.getTriggerRuleAndStoreByTriId(query.getTriId());
        return RestResponse.success(map);
    }

    /**
     * 修改触发器规则
     *
     * @param triggerRule
     * @return
     */
    @ApiOperation(value = "修改触发器规则",notes = " ")
    @ApiImplicitParam(name = "triggerRule", value = "TriggerRule")
    @RequestMapping(value = "updTriggerRule", method = RequestMethod.POST)
    public RestResponse updTriggerRule(@RequestBody TriggerRule triggerRule) {
        logger.info("修改规则参数" + JSON.toJSONString(triggerRule));

        RestResponse restResponse = checkTriggerRule(triggerRule);
        if (restResponse.getCode() != 0) {
            return restResponse;
        }
        int result = triggerRuleService.updTriggerRule(triggerRule);
        //同一个设备同一个属性已经存在了规则
//        if (result == 0) {
//            return RestResponse.error(RestCode.Trigger_Rule_Exist);
//        }

        return RestResponse.success();
    }

    /**
     * 添加存储位置
     *
     * @param triggerRuleStore
     * @return
     *//*
    @ApiOperation("添加存储位置")
    @ApiImplicitParam(name = "triggerRuleStore", value = "规则存储实体")
    @RequestMapping(value = "addTriggerRuleStore", method = RequestMethod.POST)
    public RestResponse addTriggerRuleStore(@RequestBody TriggerRuleStore triggerRuleStore) {
        if (StringUtils.isEmpty(triggerRuleStore.getTriDest())) {
            return RestResponse.error(RestCode.Tri_Desc_Null);
        }
        //判断是否有触发规则
        TriggerRule triggerRule = triggerRuleService.getTriggerRuleById(triggerRuleStore.getRuleId());
        if (triggerRule == null) {
            return RestResponse.error(RestCode.Trigger_Rule_Null);
        }
        BeanHelper.onInsert(triggerRuleStore);
        triggerRuleStoreService.addTriggerRuleStore(triggerRuleStore);
        //添加t_trigger_rule_detail
        logger.info("添加t_trigger_rule_detail：" + JSON.toJSONString(triggerRuleStore));
        //triggerRuleDetailService.insertByTriggerRuleStore(triggerRuleStore);
        return RestResponse.success();
    }

    *//**
     * 获取存储位置
     *
     * @param query
     * @return
     *//*
    @ApiOperation("获取存储位置")
    @ApiImplicitParam(name = "ruleId", value = "规则id")
    @RequestMapping(value = "getTriggerRuleStoreByRuleId", method = RequestMethod.POST)
    public RestResponse getTriggerRuleStoreByRuleId(@RequestBody TriggerRuleStore query) {
        TriggerRuleStore triggerRuleStore = triggerRuleStoreService.getTriggerRuleStoreByRuleId(query.getRuleId());
        return RestResponse.success(triggerRuleStore);
    }

    *//**
     * 修改存储位置
     *
     * @param triggerRuleStore
     * @return
     *//*
    @ApiOperation("修改存储位置")
    @ApiImplicitParam(name = "triggerRuleStore", value = "规则存储实体")
    @RequestMapping(value = "updTriggerRuleStore", method = RequestMethod.POST)
    public RestResponse updTriggerRuleStore(@RequestBody TriggerRuleStore triggerRuleStore) {
        if (StringUtils.isEmpty(triggerRuleStore.getTriDest())) {
            return RestResponse.error(RestCode.Tri_Desc_Null);
        }
        //更新存储位置
        triggerRuleStoreService.updTriggerRuleStore(triggerRuleStore);
        //添加t_trigger_rule_detail
        logger.info("添加t_trigger_rule_detail：" + JSON.toJSONString(triggerRuleStore));
        //triggerRuleDetailService.insertByTriggerRuleStore(triggerRuleStore);
        return RestResponse.success();
    }
*/
    /**
     * 根据设备标识获取触发规则
     *
     * @param triggerRule
     * @return
     */
    @RequestMapping(value = "getTriggerRuleListByDeviceIdentify", method = RequestMethod.POST)
    public List<TriggerRule> getTriggerRuleListByDeviceIdentify(@RequestBody TriggerRule triggerRule) {
        List<TriggerRule> listByDeviceIdentify = triggerRuleService.getTriggerRuleListByDeviceIdentify(triggerRule.getQueryScopDev());
        return listByDeviceIdentify;
    }

    /**
     * 根据产品id或者属性获取列表
     *
     * @param triggerRule
     * @return
     */
    @RequestMapping(value = "getListByProductIdOrProProperty", method = RequestMethod.POST)
    public List<TriggerRule> getListByProductIdOrProProperty(@RequestBody TriggerRule triggerRule) {
        List<TriggerRule> list = triggerRuleService.getListByProductIdOrProProperty(triggerRule);
        return list;
    }

    //触发器检查
    private RestResponse checkTrigger(Trigger trigger) {
        String triName = trigger.getTriName();
        String triDesc = trigger.getTriDesc();
        if (StringUtils.isEmpty(triName)) {
            return RestResponse.error(RestCode.Trigger_Name_Null);
        }
        if (trigger.getTriDataFormat() == 0) {
            return RestResponse.error(RestCode.Dataformat_NUll);
        }
        if (BeanHelper.length(triName) < 4 || BeanHelper.length(triName) > 30) {
            return RestResponse.error(RestCode.Trigger_Name_Length);
        }
        if (!StringUtils.isEmpty(triDesc) && BeanHelper.length(triDesc) > 140) {
            return RestResponse.error(RestCode.Trigger_Desc_Length);
        }
        return RestResponse.success();
    }

    //规则检查
    private RestResponse checkTriggerRule(TriggerRule triggerRule) {
        if (StringUtils.isEmpty(triggerRule.getRuleSql())) {
            return RestResponse.error(RestCode.Sql_Null);
        }
        if (StringUtils.isEmpty(triggerRule.getRuleField())) {
            return RestResponse.error(RestCode.Rule_Field_Null);
        }
        if (StringUtils.isEmpty(triggerRule.getQueryScopPro()) || triggerRule.getQueryScopPro() == 0) {
            return RestResponse.error(RestCode.Product_Null);
        }
        if (StringUtils.isEmpty(triggerRule.getQueryScopDev())) {
            return RestResponse.error(RestCode.Device_Null);
        }

        if (triggerRule.getRuleField().length() > 50) {
            return RestResponse.error(RestCode.Field_Length);
        }

        return RestResponse.success();
    }

    //判断数字小数点后两位
    private boolean isNum(String str) {
        Pattern pattern = Pattern.compile("^[+-]?\\d+(\\.\\d{0,2})?$");
        if (pattern.matcher(str).matches()) {
            return true;
        } else {
            return false;
        }
    }

    //判断中文英文数字
    private boolean isChineseEnglishNum(String str) {
        Pattern pattern = Pattern.compile("^[\\u4e00-\\u9fa5a-zA-Z\\d+]+|\\d+(\\.\\d+)+$");
        if (pattern.matcher(str).matches())
            return true;
        else
            return false;
    }

}
